import member from '@src/store/member'
import base from '@src/store/base'
import { checkPwdInit, getAccountInfoExt, getDynamicQRCode } from '@src/api/member';
import { storeBindingsBehavior } from 'mobx-miniprogram-bindings'
import $math from "@src/common/math"
import router from "@src/router";
import $cache from "@src/common/wxCache";
import { matchCardCode } from '@src/common/coupon'
import config from '@src/config'
Component({
  options: {
    addGlobalClass: true
  },
  behaviors: [storeBindingsBehavior, router.routerBehavior],
  storeBindings: [{
    store: member,
    fields: ['isMember', 'categoryName'],
    actions: ['getBaseInfo'],
  }, {
    store: base,
    fields: ['inAudit', 'themeCode', 'themeColor', 'themeTitleColor', 'perms']
  }],
  data: {
    cardImg: '',
    loading: true,
    login: false,
    hasCheck: false,
    scanModal: false,
    qrNumber: '',
    qrData: '',
    accountInfo: false,
    isPwdInit: true,
    interval: null,
    originScreenBrightness: null,
    hasInit: false,
    balance: 0,
  },
  observers: {
    'isMember': function (isMember) {
      // 会员变动刷新
      if (isMember && this.data.hasInit) {
        this.fetchData();
        this.startPoll();
      } else if (!isMember && this.data.hasInit) {
        this.resetScreenBrightness();
      }
    },
  },
  methods: {
    onLoad() {
      if (config.tpl === 'mall') {
        this.getTabBar().select("/pages/mineScan/main")
      } else { this.getTabBar().select("MEMBER_CODE") }
    },
    onShow() {
      if (this.data.isMember && this.data.hasInit) {
        this.initScreenBrightness();
        this.startPoll();
        this.checkInitPassword();
        this.refreshDynamicQRCode();
      }

      wx.nextTick(()=>{
        this.setData({ login: true, hasInit: true })
        if (this.data.isMember) {
          this.fetchData();
          this.checkInitPassword();
          this.startPoll();
          this.initScreenBrightness()
        }
      })
    },
    onHide() {
      if (this.data.interval) {
        clearInterval(this.data.interval)
        this.setData({ interval: null })
      }
      this.resetScreenBrightness();
    },
    onUnload() {
      this.resetScreenBrightness();
    },
    onLogin() {
    },
    onAnon() {
      this.setData({ login: false, hasInit: true })
    },
    onPullDownRefresh() {
      wx.stopPullDownRefresh();
    },
    fetchData() {
      this.refreshDynamicQRCode();
      getAccountInfoExt().then(res => {
        console.log('res', res)
        this.setData({ accountInfo: res.data });
        if (this.data.accountInfo.baseInfo) {
          let balance = $math.add(this.data.accountInfo.baseInfo.balance / 100, this.data.accountInfo.baseInfo.giftBalance / 100);
          // balance = $math.sub(balance, this.data.accountInfo.baseInfo.lockedBalance / 100)
          this.setData({
            balance: balance
          })
        }
      })
    },
    checkInitPassword: function (value) {
      if (this.data.hasCheck) {
        return;
      }
      checkPwdInit().then(res => {
        if (res.code === 0) {
          let isPwdInit = res.data.initialed;
          this.setData({ hasCheck: true });
          if (!isPwdInit && !$cache.get("hasCheckInitPassword")) {
            $cache.set("hasCheckInitPassword", true, 60 * 30);
            //this.showInitPasswordTip();
          }
        }
      })
    },
    showInitPasswordTip() {
      wx.showModal({
        title: "设置支付密码",
        content: "您正在使用会员动态码消费, 动态码每分钟自动刷新保证您的会员账户安全, 但是您还可以通过以下方式到店无卡消费, 建议设置支付密码配合使用\n" +
          "• 向服务员报手机号消费\n" + "• 向报微信会员卡号消费\n" + "无卡消费与动态码消费是同权的,配合支付密码可以使账户余额更安全。",
        confirmText: "设置密码",
        success: sm => {
          if (sm.confirm) {
            router.push({ name: 'member/resetPassword', params: { type: "init" } })
          }
        }
      });
    },
    initScreenBrightness() {
      //保持屏幕常亮
      wx.setKeepScreenOn({ keepScreenOn: true });
      //给屏幕亮度赋值
      wx.getScreenBrightness({
        success: res => {
          if (res.value < 0.75) {
            wx.setScreenBrightness({ value: 0.75 });
          }
          this.setData({ originScreenBrightness: res.value })
        }
      });
    },
    resetScreenBrightness() {
      wx.setKeepScreenOn({ keepScreenOn: false });
      if (this.data.originScreenBrightness) {
        wx.setScreenBrightness({ value: this.data.originScreenBrightness });
        this.setData({ originScreenBrightness: null })
      }
    },
    refreshDynamicQRCode() {
      getDynamicQRCode().then(res => {
        let qrNumber = res.data.code.replace(/(.{4})/g, "$1 ");
        this.setData({ qrData: res.data, qrNumber: qrNumber })
      })
    },

    startPoll() {
      if (this.data.interval) {
        clearInterval(this.data.interval);
      }
      let interval = setInterval(() => {
        this.refreshDynamicQRCode();
      }, 60000)
      this.setData({ 'interval': interval })
    },
    handleScanBtn() {
      wx.scanCode({
        success: res => {
          console.log('res', res);

          if (res.result) {
            if ((/^81(28|30)\d{16}$/g.test(res.result))) {
              let result = res.result;
              if (/^8128\d{16}$/g.test(result)) { router.push({ name: 'member/exchangeCoupon', params: { code: result, type: 1 } }) };
              if (/^8130\d{16}$/g.test(result)) { router.push({ name: 'member/exchangeCoupon', params: { code: result, type: 2 } }) };
            } else {
              let path = decodeURIComponent(res.result);
              console.log('path', path)
              let flag = matchCardCode(path);
              console.log('flag', flag)
              if (flag) {
                router.push({ name: 'member/exchangeCoupon', params: { code: flag.id, type: flag.type } })
              } else {
                wx.showToast({
                  title: '格式不正确',
                  icon: 'none',
                  duration: 2000
                })
              }
            }
          } else {
            wx.showToast({
              title: '格式不正确',
              icon: 'none',
              duration: 2000
            })
          }
        }
      });
    },
    handleLogin() {
      this.selectComponent("#login").requireLogin();
    },
    handleRegister() {
      this.selectComponent("#login").requireLogin().then(res => {
        router.push({ name: "indexChooseCard" })
      });
    },
    handleShowScanModel() {
      console.info("handleShowScanModel")
      this.setData({ scanModal: true });
    },
    handleCloseScanModel() {
      this.setData({ scanModal: false });
    },
  }
})
